<template>
    <view v-if="showModel" class="modal-content">
        <view class="container">
            <view class="nav-bar">
                <view class="back-btn" @click="handleClose">
                    <!-- <uni-icons type="back" size="20" color="#000"></uni-icons> -->
                    <u-icon name="home" size="40" color="#000"></u-icon>
                </view>
                <!-- <view class="nav-title">零钱明细</view> -->
            </view>
            <view class="top">
                <!-- 现金零钱卡片 -->
                <view class="money-card">
                    <view class="money-title">
                        <u-icon name="rmb-circle-fill" size="40" color="#fff"></u-icon>
                        <text class="title-text">现金零钱</text>
                    </view>
                    <view class="money-amount">
                        <text class="amount">{{ totalAmount.toFixed(1) }}</text>
                        <text class="unit">元</text>
                    </view>
                </view>
                <!-- 提现提示 -->
                <view class="withdraw-tip" v-show="remainingAmount > 0">
                    <text class="tip-text">离提现成功仅差</text>
                    <text class="tip-amount">{{ remainingAmount.toFixed(1) }}</text>
                    <text class="tip-unit">元</text>
                </view>
            </view>
            <!-- 零钱明细列表 -->
            <view class="detail-section">
                <view class="detail-title">零钱明细</view>
                <!-- 使用 scroll-view 包裹列表 -->
                <scroll-view class="detail-list" scroll-y :style="{ height: scrollHeight + 'px' }">
                    <view v-for="(item, index) in myInfo.my_reward" :key="item.id" class="detail-item animate-item" :style="{'animation-delay': index * 0.2 + 's'}">
                        <view class="item-left">
                            <view class="icon-wrapper">
                                <u-icon :name="item.icon || 'plus-people-fill'" size="40" color="#FFFFFF"></u-icon>
                            </view>
                            <view class="item-info">
                                <text class="item-title">{{ item.remark }}</text>
                                <text class="item-time">{{ item.create_time }}</text>
                            </view>
                        </view>
                        <text class="item-amount">+{{ Number(item.amount).toFixed(1) }}</text>
                    </view>
                </scroll-view>
            </view>

            <!-- 微信付款 -->
            <animationComp :showTemp="showTemp" ref="animationComp" @addAmount="addNewItem"></animationComp>
            <!-- 绑定 -->
            <effectBind ref="effectBind" @close="closePopup"></effectBind>
            <!-- 错误提示 -->
            <animationError :showText="errMsg" ref="animationError" ></animationError>
        </view>
    </view>
</template>

<script>
import animationComp from '@/components/effect-component/animation-comp.vue'
import effectBind from '@/components/effect-component/effect-bind.vue'
import animationError from '@/components/effect-component/animation-error.vue'
import store from '@/public/store.js'
import newUserRewardApi from '@/api/newUserReward.js'
const app = getApp();
export default {
    components: {
        animationComp,
        effectBind,
        animationError
    },
    data() {
        return {
            withdrawalTarget: 10, // 提现标准金额
            showModel: false,
            detailList: [
            ],
            scrollHeight: 330, // 初始高度，可以根据需要动态计算
            BestImgUrl: app.globalData.imgurl,
            myInfo: {
                difference_amount: 10,
                min_withdrawal_amount: 10,
                my_balance: 0,
                my_reward: []
            },
            showTemp: 2, // 1：显示提现 2：显示绑定
            errMsg: '',
        }
    },
    computed: {
        // 计算总金额
        totalAmount() {
            return this.myInfo.my_reward.length ? this.myInfo.my_reward.reduce((sum, item) => {
                return sum + parseFloat(item.amount);
            }, 0) : 0
        },
        // 计算距离提现还差多少
        remainingAmount() {
            const remaining = this.myInfo.min_withdrawal_amount - this.totalAmount;
            // console.log('store',store)
            console.log('remaining',remaining)
            store.commit('setWithdrawalTarget', remaining)
            return remaining > 0 ? remaining : 0;
        }
    },
    methods: {
        showUp(){
            this.showModel = true
            console.log('this.$refs.animationComp',this.$refs.animationComp)
            setTimeout(() => {
                this.$refs.animationComp.showUp()
            }, 500);
            // this.$refs.animationComp.showUp()
        },
        handleClose() {
            this.showModel = false
        },
        addNewItem(newInfo) {
            console.log('newInfo',newInfo)
            // 生成新增奖励的初始数据
            const animationTemp = this.showTemp
            
            // 逐帧更新余额
            this.animateBalanceIncrease(newInfo.amount, newInfo);
        },
        // 绑定信息
        getEffectBind() {
            this.showModel = true
            setTimeout(()=>{
                this.$refs.effectBind.showPopup()
            },500)
        },
        animateBalanceIncrease(amount,newInfo) {
            let currentAmount = 0;
            const targetAmount = 0 + Number(amount);
            const step = 0.1; // 每次增加的值
            const animationTemp = this.showTemp;
            console.log('targetAmount',targetAmount)
            const increaseBalance = () => {
                if (currentAmount < targetAmount) {
                    currentAmount += step;
                    if (currentAmount > targetAmount) {
                        currentAmount = targetAmount;
                    }
                    this.myInfo.my_reward[0].amount = currentAmount.toFixed(1);

                    // 使用 setTimeout 模拟 requestAnimationFrame
                    setTimeout(increaseBalance, 16); // 大约 60 FPS
                } else if (animationTemp === 1) {
                    // 当数据增加完成且是第三阶段时
                    setTimeout(() => {
                        this.showModel = false; // 关闭当前弹窗
                        this.$emit('showFinish'); // 触发父组件显示 effect-finish
                    }, 500);
                }
            };
            const data = {
                id: newInfo.id,
            }
            // increaseBalance();
            // return
            newUserRewardApi.setMyReward(data).then(res=>{
                const title = newInfo.title
                const newItem = {
                    id: newInfo.id,
                    remark: title,
                    time: new Date().toLocaleString(),
                    amount: 0.1,
                    icon: 'plus-people-fill'
                };
                this.myInfo.my_reward.unshift(newItem);
                // 启动动画
                increaseBalance();
                if (newInfo.type == 1) {
                    setTimeout(()=>{
                        this.$refs.effectBind.showPopup()
                    },500)
                }
            }).catch(err => {
                // console.log('errrr',err)
                this.errMsg = err.data.msg
                this.$refs.animationError.showUp()
            })
        },
        calculateScrollHeight() {
            // 获取屏幕高度
            const screenHeight = uni.getSystemInfoSync().windowHeight;
            // 获取 detail-section 距离顶部的距离
            const query = uni.createSelectorQuery().in(this);
            query.select('.detail-list').boundingClientRect(data => {
                console.log(data);
                if (data) {
                    // 计算剩余高度
                    this.scrollHeight = screenHeight - data.top - 20; // 20 是底部留白
                }
            }).exec();
        },
        // 绑定完成
        closePopup() {
            // this.showModel = false
            this.openPhonePage()
            // uni.navigateTo({
            //     url: '/mePages/pages/Bindphone?laiyuan=' + 'userReward',
            //     animationType: 'pop-in'
            // })
            return
        },
        // 绑定完成
        openPhonePage() {
            this.showModel = true
            this.showTemp = 1
            setTimeout(() => {
                this.$refs.animationComp.showUp()
            }, 500);
        }
    },
    mounted() {
        // 动态计算 scroll-view 的高度
        this.calculateScrollHeight();
        
        newUserRewardApi.getMyReward().then(res => {
            const data = res.data
            const {result, code} = data
            this.myInfo = result
            const  {myInfo} = this
            // console.log('myInfo', myInfo)
            // myInfo.my_reward.forEach(item => {
            //     this.myInfo.my_balance = Number(myInfo.my_balance) + Number(item.amount)
            //     console.log(this.myInfo.my_balance)
            // })
        })
    },
}
</script>

<style lang="less" scoped>
@import url("./less/list.less");

.nav-bar {
    position: relative;
    display: flex;
    align-items: center;
    height: 88rpx;
    background: #fff;
    padding: 0 30rpx;
    padding-top: 130rpx; //这里是状态栏css变量;
    .back-btn {
        position: absolute;
        left: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60rpx;
        height: 60rpx;
    }

    .nav-title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: 500;
        color: #000;
    }
}

.detail-section {
    margin-top: 40rpx;
}

.detail-list {
    padding-bottom: 40rpx; // 避免内容被底部遮挡
}

.animate-item {
    animation: fadeInDown 0.5s ease-out forwards;
    opacity: 0;
    transform: translateY(-40rpx);
}

@keyframes fadeInDown {
    from {
        opacity: 0;
        transform: translateY(-40rpx);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>